package com.clever.customer.service.impl;

import com.clever.commons.exception.BaseException;
import com.clever.commons.exception.StatusCode;
import com.clever.customer.request.LoginByPhoneRequestParam;
import com.clever.customer.service.CustomerService;
import com.clever.mq.callback.DefaultSendCallback;
import com.clever.redis.config.RedisKeyPrefixProperties;
import com.clever.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author ChenWang
 * @date 2020/12/12 10:48
 * @since JDK 1.8
 */
@Service
@Slf4j
public class CustomerServiceImpl implements CustomerService {
    @Value("${rocketmq.topic}")
    private String topic;
    @Resource
    RocketMQTemplate rocketMQTemplate;
    @Resource
    RedisKeyPrefixProperties redisKeyPrefixProperties;
    @Resource
    RedisService redisService;

    /**
     * 异步请求向指定电话发送验证码
     * @param phone 指定的电话号码
     * @return true表示发送成功,false表示发送失败
     */
    @Override
    public boolean askVerificationCode(String phone) {
        rocketMQTemplate.asyncSend(topic, phone, new DefaultSendCallback());
        return true;
    }

    /**
     * 简单版本的通过电话登录 无加密，没有集成第三方框架shiro
     * @param loginByPhoneRequestParam
     * @return true表示登录成功,false表示登录失败
     */
    @Override
    public boolean simpleLoginByPhone(LoginByPhoneRequestParam loginByPhoneRequestParam) {
        try{
            String captcha= (String)redisService.get(
                    String.format("%s:%s",
                            redisKeyPrefixProperties.getSmsPrefix(),
                            loginByPhoneRequestParam.getPhone()));
            if(!StringUtils.isEmpty(captcha) && captcha.equals(loginByPhoneRequestParam.getCaptcha())){
                return true;
            }else{
                throw new BaseException(StatusCode.ACCOUNT_LOGIN_ERROR);
            }
        }catch (Exception e){
            throw new BaseException(StatusCode.ACCOUNT_LOGIN_ERROR);
        }
    }

    /**
     * 集成了第三方验证框架 使用电话登录 验证码加密
     * @param loginByPhoneRequestParam  登录请求的数据
     * @return  true表示登录成功,false表示登录失败
     */
    @Override
    public boolean loginByPhone(LoginByPhoneRequestParam loginByPhoneRequestParam) {
        return false;
    }
}
